import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client extends JDialog implements Runnable{
    private JPanel panel;
    private Thread outputThread;
    private JTextField enterField;
    private JTextArea displayArea;
    private Socket client;
    private ObjectInputStream input;
    private ObjectOutputStream output;
    private String message = "";
    private PrintWriter writer;
    BufferedReader in;
 
    public Client(JFrame owner) {
        super(owner, "Client Side", false);

        JButton send, connect, close;

        enterField = new JTextField();
        enterField.setEnabled(false);
        displayArea = new JTextArea();
        displayArea.setEditable(false);

        send = new JButton("<< SEND >>");
        send.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                sendData();
            }
        });

        connect = new JButton("Connect");
        connect.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent event) {
                 start();
             }
        });

        panel = new JPanel();
        panel.add(send);
        panel.add(connect);
        //panel.add(close);

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(new JScrollPane( enterField ), BorderLayout.NORTH );
        getContentPane().add(new JScrollPane( displayArea ), BorderLayout.CENTER );
        getContentPane().add(panel, BorderLayout.SOUTH );

        reset();
        setSize( 500, 200 );
        setVisible(true);
    }

    public void start() {
        try {
            // Step 1: Create a Socket to make connection
            client = new Socket("localhost", 8000);
            System.out.println("Attemp to connect to server" + "\n");

            // Step 2: Get the input and output streams
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            writer = new PrintWriter(client.getOutputStream());

            displayArea.append( "Connected to: " + client.getInetAddress().getHostAddress()
                                + " from port: " + client.getLocalPort() + "\n");

        } catch (EOFException eofException) { // server closed connection
            System.out.println( "Server terminated connection" );
        }

        // process problems communicating with server
        catch ( IOException ioException ) {
            System.out.println("ex-1");
            ioException.printStackTrace();
        }

        // create and start output thread
        outputThread = new Thread( this );
        outputThread.start();
        enterField.enable();
    }
    
    // connect to server and process messages from server
    public void run() {
        // connect to server
        try {
            String str = in.readLine();
            displayArea.append("\n"+str);
            System.out.println(str + "\n");
        } catch (IOException ioException ) {
            ioException.printStackTrace();
            System.out.println("ex0");
        }

        while ( true ) {
            // read message from server and process message
            try {
                String message = in.readLine();
                if (message == null) {
                    displayArea.append("\n" + "disconnect!");
                    break;
                }
                else
                    displayArea.append("\n" + message);
            }catch ( IOException ioException ) {
                ioException.printStackTrace();
                System.out.println("ex1");
            }
        }
        closeConnection();
    }

    // close streams and socket
    private void closeConnection() {
        try {
            displayArea.setText( "\nClosing connection" );
            setVisible(false);
            client.close();
        } catch(Exception ex) {
            ex.printStackTrace();
            //System.out.println("Disconnect!");
        }
    }

    private void sendData() {
        
        try {
            writer.println(enterField.getText());
            writer.flush();
        } catch(Exception ex) {
                ex.printStackTrace();
                System.out.println("ex3");
        }

        enterField.setText("");
    }

    private void reset() {
        displayArea.setText("");
        enterField.setText("");
    }
}
